import Router from 'vue-router';
import Vue from 'vue';
import store from '@/store'
// import store from '../store'; // 引入 Vuex store
Vue.use(Router);


const routes = [
  {
    path: '/',
    name: 'HomePage',
    component: () => import('@/views/HomePage.vue'),
    children: [
      {
        path: '/items',
        name: 'items',
        component: () => import('@/views/admin/ItemsPage.vue'),
        meta: {
          requiresAuth: true,
          roles: ['admin'],
        }
      },
      {
        path: '/students',
        name: 'students',
        component: () => import('@/views/admin/StudentPage.vue'),
        meta: {
          requiresAuth: true,
          roles: ['admin'],
        }
      },
      {
        path: '/calendar',
        name: 'calendar',
        component: () => import('@/views/admin/CalendarPage.vue'),
        // meta: {
        //   requiresAuth: true,
        //   roles: ['admin'],
        // }
      },
      {
        path: '/index',
        name: 'index',
        component: () => import('@/views/admin/IndexPage.vue'),
        meta: {
          requiresAuth: true,
          roles: ['admin'],
        }
      },
      {
        path: '/record',
        name: 'record',
        component: () => import('@/views/admin/RecordPage.vue'),
        meta: {
          requiresAuth: true,
          roles: ['admin'],
        }
      },
      {
        path: '/info',
        name: 'info',
        component: () => import('@/views/admin/InfoPage.vue'),
        meta: {
          requiresAuth: true,
          roles: ['admin'],
        }
      }
    ]
  },
  {
    path: '/login',
    component: () => import('@/views/LoginPage.vue'),
  },
  {
    path: '/register',
    component: () => import('@/views/RegisterPage.vue'),
  },
  {
    path: '/admin',
    component: () => import('@/views/AdminPage.vue'),
    meta: {
      requiresAuth: true,
      roles: ['admin'],
    }
  },
  {
    path: '/user',
    component: () => import('@/views/UserPage.vue'),
    meta: {
      requiresAuth: true,
      roles: ['user'],
    }
  }
];

const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
});


// 获取用户角色函数
function getUserRole() {
  const role = store.state.user ? store.state.user.role : null;
  return role;
}


router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    const userRole = getUserRole();
    if (!userRole) {
      console.log("角色不符")
      next({ path: '/login' });
    } else if (to.meta.roles && to.meta.roles.indexOf(userRole) === -1) {
      next({ path: '/unauthorized' });
    } else {
      next();
    }
  } else {
    next();
  }
});


// 导航栏中用到了路由 防止重复点同一个菜单给出错误提示
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
};

export default router;
